<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use org\Http;
use org\PclZip;
use think\Db;
use app\common\model\Site;
use app\common\model\Article;
use app\common\model\User;
use app\common\model\FriendlyLink;

/**
 * 后台首页
 * Class Index
 * @package app\admin\controller
 */
class Index extends AdminBase
{
    protected function _initialize()
    {
        parent::_initialize();

    }

    public function undefined()
    {
        return $this->fetch();
    }

    /**
     * 首页
     * @return mixed
     */
    public function adminindex()
    {

        $baseUrl = str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'])) . '/';

        $root = 'http://' . $_SERVER['HTTP_HOST'] . $baseUrl;
        $version = Db::query('SELECT VERSION() AS ver');
        $config = [
            'url' => $_SERVER['HTTP_HOST'],
            'document_root' => $_SERVER['DOCUMENT_ROOT'],
            'server_os' => PHP_OS,
            'server_port' => $_SERVER['SERVER_PORT'],
            'server_soft' => $_SERVER['SERVER_SOFTWARE'],
            'php_version' => PHP_VERSION,
            'mysql_version' => $version[0]['ver'],
            'max_upload_size' => ini_get('upload_max_filesize'),
        ];

        $this->assign('root', $root);
        return $this->fetch('adminindex', ['config' => $config]);
    }

    public function home()
    {
        $oldver = Db::name('system')->where('name', 'version')->value('value');
        $otaservice = Db::name('system')->where('name', 'otaservice')->value('value');
        $arr=unserialize($otaservice);
        $updatekey=$arr['updatekey'];
        $domaininfo=checkupdate($updatekey,$oldver);
        $newVersionInfo=@$domaininfo['data']['new_version_info'];
        $this->assign('oldver', $oldver);
        $this->assign('updatekey',$updatekey);
        $this->assign('versioninfo',$newVersionInfo);
        $siteCount = (New Site())->count();
        $siteWaitCheck = (New Site())->where('status', 0)->count();
        $resourceCount = (New Article())->count();
        $resourceWaitCount=Db::name('article')->where('status',0)->count();
        $userCount=(New User())->count();
        $friendlyLinkWaitCheck = (New FriendlyLink())->where('status', 0)->count();
        $todayUpdateResCount=(New Article())->where(['created_at'=>['gt',date('Y-m-d')]])->count();
        $this->assign('tongji',
            array(
                'siteCount' => $siteCount,
                'siteWaitCheck' => $siteWaitCheck,
                'resourceCount' => $resourceCount,
                'resourceWaitCount' => $resourceWaitCount,
                'userCount' => $userCount,
                'todayUpdateResCount' => $todayUpdateResCount,
                'friendlyLinkWaitCheck' => $friendlyLinkWaitCheck
            ));
        return $this->fetch();
    }

    function updatesql($sqldir)
    {
        $db_config = array();
        $config = new \think\Config();
        $db_config['prefix'] = $config::get('database.prefix');
        $sqldata = file_get_contents($sqldir);
        $sql_array = preg_split("/;[\r\n]+/", str_replace('ls_', $db_config['prefix'], $sqldata));
        foreach ($sql_array as $k => $v) {
            if (!empty($v)) {
                Db::query($v);
            }
        }
    }

    /**
     * +----------------------------------------------------------
     * 目录下文件删除或复制
     * +----------------------------------------------------------
     * $source_dir 目录来源
     * $action_dir 目标目录
     * $del 删除模式
     * +----------------------------------------------------------
     */
    function dir_action($source_dir, $action_dir, $del = false)
    {
        if (is_dir($source_dir)) {
            $dir = opendir($source_dir);
            if (!is_dir($action_dir)) mkdir($action_dir);
            while (($file = readdir($dir)) !== false) {
                if (($file != '.') && ($file != '..')) {
                    if (is_dir($source_dir . '/' . $file)) {
                        $this->dir_action($source_dir . '/' . $file, $action_dir . '/' . $file, $del);
                    } else {
                        if ($del) {
                            unlink($action_dir . '/' . $file);
                        } else {
                            copy($source_dir . '/' . $file, $action_dir . '/' . $file);
                        }
                    }
                }
            }
            closedir($dir);
        }
    }

    /**
     * +----------------------------------------------------------
     * 解压缩文件
     * +----------------------------------------------------------
     * $zipfile 压缩包
     * $savepath 解压后的路径
     * +----------------------------------------------------------
     */
    function file_unzip($zipfile, $savepath)
    {
        //include_once (ROOT_PATH . ADMIN_PATH . '/include/pclzip.class.php');
        $archive = new PclZip($zipfile);
        if ($archive->extract(PCLZIP_OPT_PATH, $savepath)) {
            return true;
        }
    }

    public function handle($type = 'downmain', $verid)
    {
        $info = $ota_info = '';
        $res = Db::name('system')->where('name', 'otaservice')->find();
        if ($res) {
            $ota_info = unserialize($res['value']);
            if ($ota_info) {
                $htd = new Http();
                $url = $ota_info['updateurl'] . '?upkey=' . $ota_info['updatekey'] . '&type=' . $type . '&ver=' . $verid;
                $data = Http::curlGet($url);
                $arr = json_decode($data, true);
                if ($data) {
                    if ($arr['code'] == 200) {
                        $basename = $arr['name'];
                        $upsqlname = $arr['name'] . $arr['version'] . '.sql';
                        if ($type == 'downmain') {
                            $action_dir = ROOT_PATH;
                            $basename = $arr['name'] . $arr['version'];
                            //检测本地有没有包
                            $upmainsql = ROOT_PATH . 'update' . DS . $upsqlname;
                            if (is_file($upmainsql)) {
                                $this->updatesql($upmainsql);
                                unlink($upmainsql);
                                return json(array('code' => 200, 'msg' => '升级成功'));
                            }
                        } elseif ($type == 'downtpl') {
                            $action_dir = ROOT_PATH . 'template' . DS . $basename;
                        } elseif ($type == 'downaddon') {
                            $action_dir = ROOT_PATH . 'addons' . DS . $basename;
                        }
                        $dir = 'update' . DS . $basename;
                        $temp = @file_get_contents("compress.zlib://" . $arr['path']);
                        $res=file_put_contents($dir . '.zip', $temp);
                        if ($res) {
                            chmod($dir . '.zip', 0755);
                            if ($this->file_unzip($dir . '.zip', 'update' . DS)) {
                                $this->dir_action($dir, $action_dir);
                                unlink($dir . '.zip');
                                $sqldir = $dir . DS . $upsqlname;
                                if (is_file($sqldir)) {
                                    $this->updatesql($sqldir);
                                    unlink($action_dir . DS . $upsqlname);
                                }
                                delete_dir_file($dir);
                                return json(array('code' => 200, 'msg' => '操作成功'));
                            } else {
                                return json(array('code' => 200, 'msg' => '下载失败'));
                            }
                        }
                    } else {
                        return json(array('code' => 0, 'msg' => $arr['msg']));
                    }
                }
            }
        } else {
            return json(array('code' => 0, 'msg' => 'OTA信息没有配置正确'));
        }
    }

    public function hiddenbq()
    {
        file_put_contents('application/extra/sqsta.php', "<?php return ['status'=>1];");
    }
}
